<template>
  <Dropdown trigger="click" class="nav-search-dropdown">
    <div class="search-input">
      <div class="input-wrap">
        <div v-if="search == ''" class="search-type ff-regular">
          <div class="text">{{ $t('home.placeholder') }}</div>
        </div>
        <span class="search-icon">
          <img src="@/assets/images/icons/icon_search.png" alt="" />
        </span>
        <Input clearable class="input ff-regular" @on-keyup="keySearch" v-model="search" type="text"> </Input>
      </div>
      <div class="camera-icon">
        <Tooltip content="Search for similar items" placement="bottom">
          <Upload :show-upload-list="false" :headers="{
            'X-Access-Token': userToken,
            lang: 'en_US',
          }" name="imageBase64" :before-upload="handleBeforeUpload" :on-progress="onProgress" :on-success="onSuccess"
            :on-error="onError" :action="uploadURL">
            <div class="loading-wrap" v-if="uploadLoading">
              <t-loading></t-loading>
            </div>
            <div class="icon" v-else>
              <img v-if="imgUrl" class="upload-image" :src="imgUrl" alt="" />
              <img v-else src="@/assets/images/icons/icon_search_default.png" alt="" />
            </div>
          </Upload>
        </Tooltip>

      </div>
    </div>
    <DropdownMenu class="nav-search-dropdown-menu" slot="list">
      <div class="search-title">
        <span class="title">Here is a title</span>
        <span class="del">
          <Icon type="md-trash" size="18" />
        </span>
      </div>
      <div class="search-goods-list" style="margin-bottom: 20px;">
        <div class="search-goods-item">
          <span class="img"></span>
          <span class="text"><span class="hot">🔥</span>SweatshirtSweatshirt</span>
        </div>
      </div>
      <div class="search-title">
        <span class="title">Here is a title</span>
      </div>
      <div class="search-goods-list">
        <div class="search-goods-item" v-for="(item, index) in 10" :key="index">
          <span class="img"></span>
          <span class="text"><span class="hot">🔥</span>SweatshirtSweatshirt</span>
        </div>
      </div>
    </DropdownMenu>
  </Dropdown>

</template>
<script>
import { mapState } from "vuex";
import TLoading from "@/components/t-loading";
import { searchByUrl, searchSepUrl } from '@/common/search-helper'
import { toSeoFriendsChannel, isJumpWeb } from "@/common/common";
import { productImageUpload, productUpload } from "@/api/product";
import { pointUser } from "@/common/point/api-hook";//打点日志
export default {
  components: { TLoading },
  data() {
    return {
      search: '',
      form: {},
      userToken: localStorage.getItem("USER_TOKEN"),
      uploadURL: productImageUpload(),
      uploadLoading: false,
      imgUrl: "",
    }
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
      config: (state) => state.config.config,
    })
  },
  methods: {
    keySearch(typeKey) {
      if (typeKey.code == "Enter") {
        this.onSearch();
      }
    },
    handleBeforeUpload(file) {
      // 定义你的大小限制，例如2MB
      // const maxSize = 100 * 1024; // 2MB
      //
      // // 检查文件大小
      // if (file.size > maxSize) {
      //   this.handleMaxSize(file);
      //   return false;
      // }
      this.uploadLoading = true;
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        this.imgUrl = reader.result; //将_base64赋值给图片的src，实现图片预览
        this.onProductUpload(reader.result);
      };
      return false; //阻止图片继续上传，使得form表单提交时统一上传
    },
    onProductUpload(base) {
      productUpload(base, this.config.defaultPlatformChannel)
        .then((res) => {
          this.uploadLoading = false;
          this.$router.push(`/goods?id=${res.result}&type=image`);
        })
        .catch(() => {
          this.uploadLoading = false;
        });
    },
    onProgress(event, file, fileList) {
      console.log("上传的钩子", event, file, fileList);
    },
    onSuccess(response) {
      // 上传成功
      this.uploadLoading = false;
      this.form.selfieFileUrl = response.data.saveToFilename;
      this.$Message.success("上传成功");
    },
    onError(error, file) {
      this.uploadLoading = false;
      this.$Message.error("上传失败");
    },
    async onSearch() {
      // 搜索埋点
      if (this.$analytics) {
        this.$analytics.logEvent('searchGoods');
      }

      // 搜索商品
      if (!this.search) {
        this.$Message.error(this.$t("home.searchKeywords"));
        return false;
      }

      pointUser('actions', '2001');

      //搜索链接（1688、淘宝、微店）
      if (this.search.indexOf("http://") != -1 || this.search.indexOf("https://") != -1) {
        if (this.firstPageSwitchMap && this.firstPageSwitchMap.first_page_switch_customize_order == 'ENABLE' && await searchSepUrl(this.search)) {
          let searchName = await searchSepUrl(this.search);
          this.sepSearchInfo(searchName)
          return;
        }

        if (this.search.indexOf("100buy.cc") != -1) {
          isJumpWeb(this.search)
          return;
        }

        let { id, channel } = await searchByUrl(this.search);
        channel = toSeoFriendsChannel(channel);
        if (!id) {
          return this.$Message.error(this.$t("home.IncorrectSearchlink"));
        }
        const query = {
        };
        if (this.userInfo.inviteCode) {
          query.inviteCode = this.userInfo.inviteCode;
        }
        let toUrl = this.$router.resolve({
          path: `/product/${channel}/${id}`
        });
        window.open(toUrl.href, "_black");
      } else {
        this.$router.push(`/goods?text=${this.search}`);
      }
    },
    sepSearchInfo(link) {
      sessionStorage.setItem('locSepSearch', link);
      this.$router.push("/diy-order")
    },
  }
}
</script>
<style lang="less" scoped>
.nav-search-dropdown {
  flex: 1;

  /deep/ .ivu-select-dropdown {
    border-radius: 15px !important;
  }
}

.nav-search-dropdown-menu {
  width: 641px;
  padding: 25px 20px;

  .search-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 16px;
    height: 20px;

    .title {
      color: #2F333A;
      font-size: 16px;
      font-weight: 600;
    }

    .del {
      display: flex;
      width: 20px;
      height: 20px;
      align-items: center;
      justify-content: center;
      color: rgba(202, 202, 202, 1);
      cursor: pointer;

      :hover {
        color: #FF186B;
      }
    }
  }

  .search-goods-list {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;

    .search-goods-item {
      display: flex;
      align-items: center;
      width: auto;
      height: 32px;
      border-radius: 4px;
      border: 1px solid #F5F5F5;
      background: #F5F5F5;
      cursor: pointer;

      .img {
        width: 30px;
        height: 30px;
        background-color: #fff;
      }

      .text {
        color: #2F333A;
        font-size: 13px;
        display: flex;
        align-items: center;
        padding: 0 10px;
        height: 30px;
        line-height: 30px;
        white-space: nowrap;
        /* 强制文本不换行 */
        overflow: hidden;
        /* 隐藏溢出内容 */
        text-overflow: ellipsis;
        /* 显示省略号 */

        .hot {
          color: #FF186B;
          margin-right: 4px;
        }
      }
    }
  }
}



.search-input {
  display: flex;
  align-items: center;
  height: 60px;
  margin: 0 auto;
  flex: 1;
  border-radius: 20px;
  border: 1px solid #F1F1F1;

  .left {
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: center;
    min-width: 120px;
    padding: 0 32px;
    cursor: pointer;
    color: @t-title-color;
    font-size: 16px;

    .select-item {
      color: @t-title-color;
      padding: 12px;
      font-size: 16px;
    }

    .active {
      color: @primary-color;
    }

    .select-wrap {
      display: flex;
      align-items: center;

      .select-value {
        color: @t-title-color;
        font-size: 18px;
      }

      .search-arrow {
        display: block;
        margin-left: 4px;
        width: 16px;
      }
    }
  }

  .line {
    width: 1px;
    height: 24px;
    background: rgba(35, 35, 35, 0.2);
  }

  .input-wrap {
    flex: 1;
    position: relative;
    display: flex;
    align-items: center;

    .search-icon {
      display: flex;
      width: 38px;
      height: 58px;
      align-items: center;
      justify-content: center;
      margin-left: 12px;

      img {
        width: 20px;
        height: 20px;
        display: block;
      }
    }

    .search-type {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      position: absolute;
      width: fit-content;
      top: 0;
      bottom: 0;
      padding-left: 55px;

      .text {
        width: 250px;
        overflow: hidden;
        text-overflow: ellipsis;
        font-weight: 500;
        font-size: 16px;
        color: #AEB0B9;
        line-height: 19px;
        text-align: left;
        font-style: normal;
        text-transform: none;
        white-space: nowrap;
      }
    }
  }

  .input {
    width: 100%;
    background: rgba(0, 0, 0, 0);
    border: 0;
    padding-right: 24px;
    height: 40px;
    font-size: 18px;

    &:hover {
      border: 0;
    }

    &:focus {
      border: 0;
    }

    :deep(.ivu-input) {
      border: 0;
      height: 100%;
      font-size: 18px;
      background: transparent;

      &::placeholder {
        color: @t-title-color;
        font-weight: 400;
        font-size: 18px;
      }
    }

    outline: none;
  }

  .camera-icon {
    position: relative;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 64px;
    height: 100%;
    padding: 12px;

    :deep(.ivu-upload) {
      display: block;
    }

    .upload-image {
      display: block;
      width: 100%;
      max-height: 100%;
    }

    .icon {
      display: block;
      width: 40px;
      height: 40px;

      img {
        cursor: pointer;
        display: block;
        width: 100%;
      }
    }
  }
}
</style>